//
//  AgentApplyViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/3/2.
//  Copyright © 2021 王洋. All rights reserved.
//
#import <BRPickerView/BRStringPickerView.h>

#import "CommonGoldAgentModel.h"
#import "ApplyAgentHandleModel.h"


#import "HomeCityPickerViewController.h"
#import "AgentReviewViewController.h"
#import "AgentDetailViewController.h"
#import "AgentApplyViewController.h"

@interface AgentApplyViewController ()<CityPickerDelegate>

@property (weak, nonatomic) IBOutlet UIView *applyGoldControl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *applyGoldHeight;


@property (weak, nonatomic) IBOutlet UILabel *cityLab;
@property (weak, nonatomic) IBOutlet UIView *cityControl;
@property (nonatomic, strong) UITapGestureRecognizer *cityTap;

@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

@property (weak, nonatomic) IBOutlet UIView *agentViewBG;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *agentControlHeight;
@property (weak, nonatomic) IBOutlet UIView *agentControlBG;

@property (weak, nonatomic) IBOutlet UIButton *selSuperiorBtn;
@property (weak, nonatomic) IBOutlet UILabel *SuperiorLab;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *selSuperiorBtnWidth;


@property (weak, nonatomic) IBOutlet UILabel *xieyiLab;

@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UIView *agreeControl;
@property (weak, nonatomic) IBOutlet UILabel *agreementLab;


@property (weak, nonatomic) IBOutlet UIButton *handleBtn;

@property (nonatomic, strong) HomeCityPickerViewController *cityPickerVC;

@property (nonatomic, strong) BRStringPickerView *stringPickerView;
@property (nonatomic, strong) NSMutableArray <NSString *>*goldAgentNames;
@property (nonatomic, strong) NSMutableArray <CommonGoldAgentModel *>*goldAgentDataArray;

@property (nonatomic, strong) ApplyAgentHandleModel *handleModel;

@property (nonatomic, assign) BOOL isAgree;

@end

@implementation AgentApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    
    //重新申请
    if (self.model.arId.length > 0) {
        [self fillApplyData];
    }
    
    //扫码进入
    if (self.agentModel.recId.length > 0) {
        [self lockGoldAgent];
    }
}

- (void)fillApplyData {
    
    self.handleModel.arId = self.model.arId;
    
    self.handleModel.cityId = self.model.cityId;
    self.cityLab.text = self.model.cityName;
    self.cityLab.textColor = UIColorHex(0x333333);

    if (self.handleModel.cityId.length > 0) {
        [self request_citySuperiorWith:self.handleModel.cityId];
    }

    self.handleModel.name = self.model.name;
    self.nameTF.text = self.model.name;
    
    self.handleModel.phone = self.model.phone;
    self.phoneTF.text = self.model.phone;
    
    self.handleModel.recommendId = self.model.recommendId;
    [self refreshSuperiorLabWithTitle:self.model.recommendName];
    [self refreshSelSuperBtnWithTitle:@"修改"];
}

- (void)lockGoldAgent {
        
    //禁止选择城市、禁止选择推荐官
    self.selSuperiorBtn.enabled = NO;
    [self.cityControl removeGestureRecognizer:self.cityTap];

    self.cityLab.text = self.agentModel.cityName;
    self.cityLab.textColor = UIColorHex(0x333333);
    
    self.handleModel.cityId = self.agentModel.cityId;
    self.handleModel.recommendId = self.agentModel.recId;

    [self refreshSuperiorLabWithTitle:self.agentModel.recommendName];
    [self refreshSelSuperBtnWithTitle:@"修改"];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.agentViewBG pp_clipCorners:UIRectCornerAllCorners radius:4 border:0.5 color:UIColorHex(0xE0E3E9)];
        [self.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:self.handleBtn.frame.size.height/2];
    });

    self.selSuperiorBtn.layer.cornerRadius = self.selSuperiorBtn.frame.size.height/2;
    self.selSuperiorBtn.layer.borderWidth = 0.5;
}

- (void)initView {
    self.title = @"推荐官申请";
    self.view.backgroundColor = UIColor.whiteColor;
        
    self.handleModel.userId = [TTUserModel sharedObject].userId;
    [self refreshSuperiorLabWithTitle:@"选择对应上级"];
    [self refreshSelSuperBtnWithTitle:@"选择上级"];
    
    NSString *xieyiStr = @"我已阅读并同意《婚前婚后服务协议》";
    self.isAgree = NO;
    [self.agreeBtn setImage:[UIImage imageNamed:@"common_nor"] forState:UIControlStateNormal];
    //富文本
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:xieyiStr];
    NSRange countRange = NSMakeRange(7, 10);
    // 设置字体大小
    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:countRange];
    self.xieyiLab.attributedText = attrStr;
    
    // gradient
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,TTScreenWidth,32);
    gl.startPoint = CGPointMake(1.08, 0.5);
    gl.endPoint = CGPointMake(0, 0.5);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:184/255.0 blue:126/255.0 alpha:0.08].CGColor, (__bridge id)[UIColor colorWithRed:255/255.0 green:114/255.0 blue:0/255.0 alpha:0.08].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    
    [self.applyGoldControl.layer insertSublayer:gl atIndex:0];
    
    WEAKSELF
    self.cityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selCity)];
    self.cityControl.userInteractionEnabled = YES;
    [self.cityControl addGestureRecognizer:self.cityTap];
    
    self.xieyiLab.userInteractionEnabled = YES;
    [self.xieyiLab addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        
        [[BA_BusinessHelper shared] callSimpleWebWith:[NSString stringWithFormat:@"%@/%@", BA_GlobalPdf_Domain, kServicePdf] htmlStr:@""];
    }];
        
    self.stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        
        [weakSelf refreshSuperiorLabWithTitle:resultModel.value];
        [weakSelf refreshSelSuperBtnWithTitle:@"修改"];
        //取值
        weakSelf.handleModel.recommendId = weakSelf.goldAgentDataArray[resultModel.index].recId;
    };
    
    [RACObserve(self.nameTF, text) subscribeNext:^(id x) {
        self.handleModel.name = self.nameTF.text;
    }];
    
    [RACObserve(self.phoneTF, text) subscribeNext:^(id x) {
        self.handleModel.phone = self.phoneTF.text;
    }];
    
    [self configApplyNormalStatus];
}

- (void)selCity {
    self.cityPickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:self.cityPickerVC animated:YES completion:nil];
}

//弹出选择上级按钮
- (IBAction)selSuperiorAction:(id)sender {
    
    [self.view endEditing:YES];
    if (self.goldAgentNames.count > 0) {
        self.stringPickerView.dataSourceArr = self.goldAgentNames.mutableCopy;
        [self.stringPickerView show];
    } else {
        [SVProgressHUD showErrorWithStatus:@"请先选择所在城市"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

- (IBAction)agreeAction:(id)sender {
    self.isAgree = !self.isAgree;
    [self.agreeBtn setImage:[UIImage imageNamed:self.isAgree?@"common_sel":@"common_nor"] forState:UIControlStateNormal];
}

- (IBAction)handleAction:(id)sender {
    [self.view endEditing:YES];

    if (self.handleModel.cityId.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择城市"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    if (self.handleModel.name.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写姓名"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    if (self.handleModel.phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写手机号"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    //普通模式下&&没选择推荐官
    if (self.goldAgentDataArray.count > 0 && self.handleModel.recommendId.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请选择金牌推荐官"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    //普通模式下&&没有选择同意协议
    if (self.goldAgentDataArray.count > 0 && !self.isAgree) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并同意《婚前婚后服务协议》"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    //重复申请模式下
    if (self.model.arId.length > 0 && !self.isAgree) {
        //申请的是金牌
        if (self.goldAgentDataArray.count > 0 && !self.isAgree) {
            [SVProgressHUD showErrorWithStatus:@"请阅读并同意《婚前婚后服务协议》"];
            [SVProgressHUD dismissWithDelay:1];
            return;
        } else {
            
        }
    }
    
    //扫码模式下没有选择同意协议
    if (self.agentModel.recId.length > 0 && !self.isAgree) {
        [SVProgressHUD showErrorWithStatus:@"请阅读并同意《婚前婚后服务协议》"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    //扫码进入提交
    if (self.agentModel.recId.length > 0) {
        [self request_QRCodeApply];
    } else {
        [self request_handleApply];
    }
    
}

#pragma mark - CityPickerDelegate
//点击后传值
- (void) cityPickerController:(CityPickerController *)cityPickerViewController didSelectCity:(CityModel *)city {
    self.cityLab.text = city.cityName;
    self.cityLab.textColor = UIColorHex(0x333333);
    [self.cityPickerVC dismissViewControllerAnimated:YES completion:nil];

    self.handleModel.cityId = city.cityID;
    [self request_citySuperiorWith:city.cityID];
    
    //需要重置推荐官
    [self refreshSuperiorLabWithTitle:@"选择对应上级"];
    [self refreshSelSuperBtnWithTitle:@"选择上级"];
    self.handleModel.recommendId = @"";

}

- (void)configApplyGoldStatus {
    if (self.model.arId.length > 0) {
        self.handleModel.arId = @"";
        self.handleModel.recommendId = @"";
    }
    
    self.title = @"金牌推荐官申请";
    self.goldAgentNames = @[].mutableCopy;
    self.goldAgentDataArray = @[].mutableCopy;
    [self refreshSuperiorLabWithTitle:@"选择对应上级"];
    [self refreshSelSuperBtnWithTitle:@"选择上级"];
    
    self.agentControlBG.hidden = YES;
    self.agreeControl.hidden = YES;
    self.applyGoldControl.hidden = NO;
    self.applyGoldHeight.constant = 32;
    self.agentControlHeight.constant = CGFLOAT_MIN;    
    [Utilities showToast:@"该城市暂无金牌推荐官" FColor:UIColor.whiteColor BColor:UIColorHex(0xff7200) BLayerColor:UIColor.clearColor];
}

- (void)configApplyNormalStatus {
    self.title = @"推荐官申请";
    self.agentControlBG.hidden = NO;
    self.agreeControl.hidden = NO;
    self.applyGoldControl.hidden = YES;
    self.applyGoldHeight.constant = CGFLOAT_MIN;
    self.agentControlHeight.constant = 113;
}

- (void)refreshSuperiorLabWithTitle:(NSString *)title {
    self.SuperiorLab.text = title;
}

//重新计算按钮布局
- (void)refreshSelSuperBtnWithTitle:(NSString *)title {
    
    if ([title isEqualToString:@"选择上级"]) {
        self.handleModel.recommendId = @"";
        self.selSuperiorBtn.layer.borderColor = UIColorHex(0xFF7200).CGColor;
        [self.selSuperiorBtn setImage:[UIImage imageNamed:@"trangle_right_orange"] forState:UIControlStateNormal];
        [self.selSuperiorBtn setTitleColor:UIColorHex(0xff7200) forState:UIControlStateNormal];
    } else if ([title isEqualToString:@"修改"]) {
        self.selSuperiorBtn.layer.borderColor = UIColorHex(0x666666).CGColor;
        [self.selSuperiorBtn setImage:[UIImage imageNamed:@"trangle_right_gray"] forState:UIControlStateNormal];
        [self.selSuperiorBtn setTitleColor:UIColorHex(0x666666) forState:UIControlStateNormal];
    }
    
    [self.selSuperiorBtn setTitle:title forState:UIControlStateNormal];
    CGFloat left = [Utilities getStringWidthWithString:title fontSize:14 andHeight:26];
    self.selSuperiorBtn.imageEdgeInsets = UIEdgeInsetsMake(0, left + 18, 0, 0);
    self.selSuperiorBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 18);
    self.selSuperiorBtnWidth.constant = left + 40;
    
    
}

- (void)cityPickerControllerDidCancel:(CityPickerController *)cityPickerViewController {
}

- (HomeCityPickerViewController *)cityPickerVC {
    if (!_cityPickerVC) {
        _cityPickerVC = [[HomeCityPickerViewController alloc] init];
        [_cityPickerVC.cityPickerVC setDelegate:self];
    }
    return _cityPickerVC;
}

- (BRStringPickerView *)stringPickerView {
    if (!_stringPickerView) {
        /// 1.单列字符串选择器（传字符串数组）
        _stringPickerView = [[BRStringPickerView alloc]init];
        _stringPickerView.pickerMode = BRStringPickerComponentSingle;
        _stringPickerView.title = @"选择所属金牌推荐官";
    }
    return _stringPickerView;
}

- (ApplyAgentHandleModel *)handleModel {
    if (!_handleModel) {
        _handleModel = [[ApplyAgentHandleModel alloc] init];
    }
    return _handleModel;
}

//请求这个城市的金牌推荐官
- (void)request_citySuperiorWith:(NSString *)cityId {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_GoldAgentList];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:cityId forKey:@"cityId"];
    [SVProgressHUD showWithStatus:@"正在获取当前城市金牌推荐官"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.goldAgentNames = @[].mutableCopy;
                weakSelf.goldAgentDataArray = @[].mutableCopy;
                NSArray *resultArray = [data valueForKey:@"data"];
                if ([resultArray isKindOfClass:[NSArray class]]) {
                    
                    if (resultArray.count != 0) {
                        [weakSelf configApplyNormalStatus];//有金牌推荐官就申请推荐官
                    } else {
                        [weakSelf configApplyGoldStatus];//没有金牌推荐官就申请金牌推荐官
                    }
                    for (NSDictionary *agentDic in resultArray) {
                        CommonGoldAgentModel *model = [CommonGoldAgentModel modelWithDictionary:agentDic];
                        [weakSelf.goldAgentDataArray addObject:model];
                        [weakSelf.goldAgentNames addObject:model.recommendName];
                    }
                } else {
                    [weakSelf configApplyGoldStatus];//没有金牌推荐官就申请金牌推荐官
                }
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
    
}

//请求提交信息
- (void)request_handleApply {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_ApplyRecommender];
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    dic = [self.handleModel modelToJSONObject];
    [SVProgressHUD showWithStatus:@"正在提交"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];

            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

//请求提交信息
- (void)request_QRCodeApply {
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CodeAddRecommender];
    NSMutableDictionary *dic = @{}.mutableCopy;
    
    dic = [self.handleModel modelToJSONObject];
    [SVProgressHUD showWithStatus:@"正在提交"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [SVProgressHUD showSuccessWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                
            } else {
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}

@end
